package com.self.reflect;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 作者：tianjiayuan
 * 创建时间：2018-06-13 13:23
 * 类描述：
 * 修改人：
 * 修改时间：
 */
public class ProxyServer {

    public void openServer(int port) {
        try {
            ServerSocket server = new ServerSocket(port);

            for(;;) {
                Socket socket = server.accept();
                InputStream in = null;
                OutputStream os = null;
                in = socket.getInputStream();
                os =socket.getOutputStream();
                byte[] bytes = new byte[1024];
                StringBuilder builder = new StringBuilder();
                int index;
                int len;
                String temp;
                while ((len = in.read(bytes)) != -1) {
                    temp = new String(bytes, "utf-8");
                    if ((index = temp.indexOf("eof")) != -1) {
                        builder.append(temp.substring(0, index));
                        break;
                    }
                    builder.append(temp);
                }
                if (builder.length() <= 0) {
                    socket.close();
                    os.close();
                } else {
                    String str = new ClientInvoker<String>().invoke(builder.toString());
                    str += "\n";
                    os.write(str.getBytes("utf-8"));
                    os.flush();
                    os.close();
                }

                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ProxyServer server = new ProxyServer();
        server.openServer(9000);
    }
}
